package com.taptech.doufu.util;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.taptech.doufu.sdk.universalimageloader.core.ImageLoader;
import com.taptech.doufu.sdk.universalimageloader.core.assist.FailReason;
import com.taptech.doufu.sdk.universalimageloader.core.assist.ImageLoadingListener;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.net.httputils.DownloadTask;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtil2
{

    public static void saveImageAsFile(final Context context, final String fileName, final String imageUrl , boolean isGif)
    {
        if (isGif){
            downLoadFileFromUrl(context , fileName , imageUrl , ".gif");
        }else {
            saveImageAsFile(context , fileName , imageUrl);
        }

    }

    public static void saveImageAsFile(final Context context, final String fileName, final String imageUrl)
    {
        ImageLoader.getInstance().loadImage(imageUrl, new ImageLoadingListener()
        {
            @Override
            public void onLoadingStarted(String imageUri, View view)
            {

            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason)
            {

            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage)
            {
                // FileOutputStream out = null;
                try
                {
                    // out = new FileOutputStream(fileName);
                    // loadedImage.compress(Bitmap.CompressFormat.PNG, 100, out);
                    saveMyBitmap(loadedImage, fileName);
                } catch (Exception e)
                {
                    e.printStackTrace();
                } finally
                {
                    try
                    {
                        Toast.makeText(context, "下载成功，图片已保存至:" + Constant.AppDir.DIR_HOME + imageUri.hashCode() + ".jpg", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri uri = Uri.fromFile(new File(Constant.AppDir.DIR_HOME + imageUrl.hashCode() + ".jpg"));
                        intent.setData(uri);
                        context.sendBroadcast(intent);
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view)
            {

            }
        });
    }

    public static void saveMyBitmap(Bitmap mBitmap, String fileName)
    {
        File f = new File(fileName);
        FileOutputStream fOut = null;
        try
        {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        try
        {
            fOut.flush();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        try
        {
            fOut.close();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }




    //保存文件到指定路径
    public static boolean saveImageToGallery(Context context, Bitmap bmp,String fileName) {
        // 首先保存图片
        String storePath= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()+File.separator+"doufu"+File.separator;

        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片
            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 80, fos);
            fos.flush();
            fos.close();

            //把文件插入到系统图库
            //MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);

            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void downLoadFileFromUrl(Context context , String fileName , String fileUrl , String expandName){
        DownloadTask downloadTask = new DownloadTask(context);
        downloadTask.startDownload(fileName , fileUrl , expandName);
    }

    // For to Delete the directory inside list of files and inner Directory
    public static boolean deleteAllWithPath(String path) {
        try {
            return FileUtil2.deleteDir(new File(path));

        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    // For to Delete the directory inside list of files and inner Directory
    private static boolean deleteDir(File dir) {
        if (dir == null) return false;
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        // The directory is now empty so delete it
        return dir.delete();
    }




}
